<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  
  <style>
    * { margin:0px; padding:0px; border-width:0px;}
  
    #header  
    { 
      /*background-color:yellow; */
      height:64px; 
      /*width:100%; */
      border:1px solid #3B5998;
    }
    #theirs
    {
      height: 64px; 
      width:99%; 
      padding-top:8px;
      /*border-bottom: 1px solid White*/
    }

    #theirs-picture
    {
      float: left;
      height: 50px;
      width: 50px;
      background-color: #3B5998;
    }

    #theirs-body
    {
      padding-left: 64px;
    }

    #theirs-name
    {
      height: 16px;
      color:#3B5998; 
      font-size: 13px;
      font-weight: bold;
      font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
      cursor: pointer;
    }

    .name
    {
      color:#3B5998; 
      font-size: 13px;
      font-weight: bold;
      font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
    }
    #theirs-flags
    {
      height: 16px;
    }

    #theirs-status
    {
      float: left;
      height: 16px;
      font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
      font-size: 12px;
      font-weight: bold;
      color: OrangeRed;
      background-color:Cornsilk; 
      border-width:1px; 
      border-color:Brown;
      border-style:solid;
      padding-left: 4px;
      padding-right: 4px;
      vertical-align: Center;
    }

  body {
        font: 12px/18px Arial, Tahoma, Verdana, sans-serif;
        overflow:hidden;
        /*height: 100%;
        width: 100%;*/
  }

  
  #content { /*background-color:gray;*/ height:100%; width:100%; }
  #footer  
  { 
    background-color:#3B5998;  
    height:64px; 
    width:100%; 
    padding:4px;
  }
  
  #text-message 
  { 
    display:block;
    overflow: auto; 
    resize: none;
    float:left;
    width:400px;
    height:52px;
  }

  #chat-window 
  { 
    height:100%;
    width:100%; 
    overflow:auto;   
  }
  
  #send
  { 
    font: 12px/18px Arial, Tahoma, Verdana, sans-serif;
    border-radius: 3px; 
    margin-left: 12px; 
    padding: 4px 4px 3px; 
    cursor: pointer;
  }
  
  #ctrl-enter
  {
    font: 12px/18px Arial, Tahoma, Verdana, sans-serif;
    color: #D8DFEA; 
    margin-left: 415px; 
  }
  
  </style>
  
  <script src="./core/event.js"></script>
<script>

function parseURIQuery(query) 
{
  var data = {};
  if (!query) return data;
  
  var pair = ( query.substring(1) ).split('&');
  
  for(var i = 0; i < pair.length; i ++) 
  {
    var param = pair[i].split('=');
    data[ param[0] ] = decodeURIComponent(param[1]);
  }
  return data;
}

function OnPublish(message)
{
  try
  {
    // document.getElementById("chat-window").innerHTML += "<div> " + me.name +": <![CDATA["+ message.content + "]]> </div>";
    var from = "Unk";
    if (message.content.from == me.id)
      from = me.name;
    if (message.content.from == theirs.id)
      from = theirs.name;

    var d = new Date(message.content.date);

    var text = "["+d.toLocaleTimeString()+"] "+from + ": " +  message.content.text;
    
    /// <span class='name'> </span>
    var divm = document.createElement("div");
    divm.appendChild( document.createTextNode( text ) );

    var chatDiv = document.getElementById("chat-window");
    
    chatDiv.appendChild( divm ) ;
    chatDiv.scrollTop = chatDiv.scrollHeight;
  }
  catch(e) 
  {
    alert("0: " + e.message)
  }
}


function OnPublish2(message)
{
  try
  {
    var divm = document.createElement("div");
    divm.appendChild( document.createTextNode( me.name +": " + message.content ) );
    document.getElementById("chat-window").appendChild( divm ) ;
  }
  catch(e) 
  {
    alert("3: " + e.message)
    alert(document);
    alert(document.createElement);
  }
}

function OnTheirsWrite(message)
{
  try
  {
    if ( message.content.type=="write" )
    {
      if ( message.content.text )
        document.getElementById("theirs-write").innerHTML = "<i>пишет: </i>" + message.content.text;
      else
        document.getElementById("theirs-write").innerHTML = "";
    }
    else if ( message.content.type=="sended" )
    {
      document.getElementById("theirs-write").innerHTML = "<i>отправил...</i>";
    }
    else if ( message.content.type=="enter" )
    {
      document.getElementById("theirs-write").innerHTML = "<i>вошел в чат</i>";
    }
    else if ( message.content.type=="exit" )
    {
      document.getElementById("theirs-write").innerHTML = "<i>вышел из чата</i>";
    }
  } 
  catch(e) 
  {
    alert( "1:" + e.message);
  }
}

function createMessage(fromId, toId, channelName, textMessage )
{
  var d = new Date();
  return {
    channel:channelName,
    limit: 10,
    lifetime: 60,
    identity: message_id.toString(),
    // TODO: как сервер будет готов
    // key: toId,
    content: {
      mid: message_id,
      text: textMessage,
      from: fromId,
      to: toId,
      date: d.toUTCString()
    }
  };
}

function createMessageNotify(toId, textMessage )
{
  var d = new Date();
  return {
    channel:"faceonline.notifier."+toId,
    limit: 10,
    lifetime: 60,
    identity: theirsChannel,
    // TODO: как сервер будет готов
    // key: toId,
    content: {
      category: "private-chat",
      type: "message",
      picture: me.picture,
      head: me.name,
      text: textMessage,
      params: { id:me.id, name: me.name, picture: me.picture }
    }
  };
}

function createInviteNotify(toId)
{
  var d = new Date();
  return {
    channel:"faceonline.notifier."+toId,
    limit: 10,
    lifetime: 60,
    identity: theirsChannel,
    // TODO: как сервер будет готов
    // key: toId,
    content: {
      category: "private-chat",
      type: "invite",
      picture: me.picture,
      head: me.name,
      text: "",
      params: { id:me.id, name: me.name, picture: me.picture }
    }
  };
}


function OnSend() { try
{
  //alert(window.theirsChannel);
  var textMessage = document.getElementById("text-message").value;
  if ( !textMessage )
    return;

  comet.simplePublish( window.meWriteChannel, { type:"sended" } );

  /*
  comet.simplePublish( window.theirsChannel,  document.getElementById("text-message").value );
  comet.simplePublish( window.meChannel,      document.getElementById("text-message").value );
  */


  ++message_id;

  messages = 
  [
    createMessage(me.id, theirs.id, meChannel, textMessage ),
    createMessage(me.id, theirs.id, theirsChannel, textMessage ),
    createMessageNotify( theirs.id, textMessage )
  ];
  //alert(messages);
  comet.publish(messages);
  document.getElementById("text-message").value = "";
} catch(e) { alert(e.message) } }

function OnPress(event)
{
  if((event.ctrlKey) && ((event.keyCode == 0xA)||(event.keyCode == 0xD)))
  {
    OnSend();
    return;
  }
  
  if ( document.getElementById("text-message").value )
  {
    var str = document.getElementById("text-message").value;
    if ( str.length > 50 )
      str = "..." + str.substring( str.length - 50 );
    comet.simplePublish(window.meWriteChannel, { type:"write", text:str } );
  }
  else
  {
    comet.simplePublish(window.meWriteChannel, { type:"write", text:"" } );
  }
  //alert("pres")
}

function Dispose() { try { 
  // alert('OnUnload');
  comet.simplePublish( window.meWriteChannel, { type:"exit" } );
  window.comet.describe(window.meChannel, OnPublish);
  window.comet.describe(window.theirsWriteChannel, OnTheirsWrite);

} catch(e) { alert(e.message) } }

function OnLoad() { try{

  
  message_id = 0;
  document.getElementById("content").style.height = (window.innerHeight - 128) + "px" ;
  window.comet = window.parent.comet;
  window.model = window.parent.model;
  window.ctrl = window.parent.ctrl;
  window.launcher = window.parent.launcher;

  
  var json = parseURIQuery( window.location.search).params;  
/*
  var json = "";  
  if ( window.location.search )
  {
    var components = window.location.search.substring(1).split('&');
    for (var i=0; i < components.length; ++i)
    {
      var keyvalue = components[i].split("=");
      if (keyvalue[0]=="params")
      {
        json = decodeURIComponent( keyvalue[1] );
      }
    }
  }
 */

  //document.getElementById("log").innerHTML = json;

  var params = JSON.parse(json);

  window.me = model.me;
  window.theirs = params/*model.me.friends[params.id]*/;

  
  document.getElementById("theirs-name").innerHTML= window.theirs.name;
  document.getElementById("theirs-picture").innerHTML= "<img src='" + window.theirs.picture + "'/>" ;

  //document.getElementById("log").innerHTML += window.theirs.name;

  window.theirsChannel = "faceonline.private-chat."+window.theirs.id+"-"+me.id;
  window.meChannel = "faceonline.private-chat."+me.id+"-"+window.theirs.id;
  window.theirsWriteChannel = window.theirsChannel+".write";
  window.meWriteChannel = window.meChannel+".write";
  
  window.comet.subscribe(window.meChannel, OnPublish);
  // window.comet.subscribe(window.theirsChannel, OnPublish2);
  window.comet.subscribe(window.theirsWriteChannel, OnTheirsWrite);
  
  /*
  document.getElementById("log").innerHTML += "<div>"+window.meChannel+"</div>";
  document.getElementById("log").innerHTML += "<div>"+window.theirsChannel+"</div>";
  */

  window.comet.open( {channel:window.meChannel, cursor:1, min_size:1, max_size:20} );
  // window.comet.open( {channel:window.theirsChannel} );
  window.comet.open( {channel:window.theirsWriteChannel, cursor:1, min_size:1, max_size:2} );
  //window.comet.process();

  Event.add(document.getElementById("send"), "click", OnSend)
  Event.add(document.getElementById("text-message"), "keyup", OnPress)
  
  comet.simplePublish( window.meWriteChannel, { type:"enter" } );
  comet.publish( createInviteNotify( theirs.id ) );
  
} catch(e) { alert("2:" + e.message);} }

Event.add(window, 'load', OnLoad)
// Event.add(window, 'close', OnUnload)

</script>

<body>

<!--
<table id="main" height="100%">

  <tr><td id="header">
   <div id="theirs-write"> </div>
  </td></tr>

  <tr height="100%"><td id="content" >
    <div id="chat-window"> </div>
  </td></tr>

  <tr><td id="footer">

  <div id="me-window"> 
    <input id="text-message" type="text" width="40" />
    <input id="send" type="button" value="send">  </input>
  </div>
  <div id="log"></div>

  </td></tr>
</table>
-->

<div id="header">

  <div id="theirs">
    <div id="theirs-picture"></div>
    <div id="theirs-body">
      <div id="theirs-name"></div>
      <div id="theirs-write"></div>
    </div>
  </div>

</div>

<div id="content"> 
  <div id="chat-window"> </div> 
  <!-- <marquee id="chat-window" behavior="slide" direction="up"> -->
  </marquee>
</div>

<div id="footer">
  <div id="me-window"> 
    <!-- <input id="text-message" type="text" width="40" /> -->
    <textarea id="text-message" minlength="1"></textarea>
    <input id="send" type="button" value="Отправить">  </input>
    <div id="ctrl-enter">CTRL+Enter</div>
  </div>
  <!-- <div id="log"></div> -->
</div>



<!--
<h1>Типа чат!</h1>
<div id="main">
  <div id="theirs-write"> </div>
  <div id="chat-window"> </div>
  <div id="me-window"> 
    <input id="text-message" type="text" width="40" />
    <input id="send" type="button" value="send">  </input>
   </div>

   <div id="log"></div>
</div>
-->
</body>
</HTML>
